package com.zed.code.service.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zed.code.util.GDEVConfig;
import com.zed.code.util.PubFetchTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.text.SimpleDateFormat;

/**
 * 对传回供应商的进行进行加密
 *
 */
@ControllerAdvice("com.zed.code.controller")
public class IResponseBodyAdvice implements ResponseBodyAdvice {

    private static final Logger logger = LoggerFactory.getLogger(IResponseBodyAdvice.class);


    
    public boolean supports(MethodParameter methodParameter, Class httpMessageConverterType) {
        return true;
    }

    
    public Object beforeBodyWrite(Object object, MethodParameter methodParameter, MediaType mediaType, Class httpMessageConverterType, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        logger.info("加密前的数据:{}", JSON.toJSONString(object));
        JSONObject json = JSON.parseObject(JSON.toJSONString(object));
        String data = json.containsKey("Data") ? json.getString("Data") : null;
        String ret = json.containsKey("Ret") ? json.getString("Ret") : null;
        String msg = json.containsKey("Msg") ? json.getString("Msg") : null;
        logger.info("data:{}", data);
        try{
            if (data!=null) {
                String retdata = PubFetchTool.genDDEncodeData( data, GDEVConfig.AES_KEY,GDEVConfig.AES_IV);
                logger.debug("加密后的数据{}AES_KEY={}AES_IV={}", retdata,GDEVConfig.AES_KEY,GDEVConfig.AES_IV);
                logger.debug("sig数据Ret={}Msg={}",ret,msg);
                json.put("Data", retdata);
                String sig = PubFetchTool.genDDSig(ret+msg+retdata,GDEVConfig.SIGN_KEY);
                json.put("Sig", sig);
            }
        }catch(Exception e){
            logger.error("com.zed.code.controller.notify data error", e);
        }
        logger.info("com.zed.code.controller.notify data: com.zed.code.response{}", json);
        return json;
    }
}
